package com.csc531.edit;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import com.csc531.R;

public class FriendsEdit extends Activity 
{

	//logging
	private static final String TAG = "friends edit";

	public static final String CLASSMATE_STRING = "classmate";
	public static final String EMPTY_STRING = "";
	
	static ArrayList<String> _people;

	//View fields
	AutoCompleteTextView _friendPeopleText;
	private EditText _friendPhoneText;
	private EditText _friendEmailText;

	//Confirm button
	private Button _confirmButton;


	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_edit);

		populatePeopleArrayList();

		ArrayAdapter<String> peopleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, _people);

		_friendPeopleText = (AutoCompleteTextView) findViewById(R.id.friend_suggest);
		_friendPeopleText.setAdapter(peopleAdapter);
		_friendPhoneText = (EditText) findViewById(R.id.friend_number);
		_friendEmailText = (EditText) findViewById(R.id.friend_email);
		
		_confirmButton = (Button) findViewById(R.id.confirm);

		dealWithTaskData(savedInstanceState);
	}

	/**
	 * @param confirmButton the confirm button
	 * @param savedInstanceState application saved instance
	 */
	private void dealWithTaskData(Bundle savedInstanceState) 
	{
		populateFields();
		_confirmButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view) 
			{
				setResult(RESULT_OK);
				finish();
			}

		});
	}


	/**
	 * Populates an array list with the people from the phone
	 */
	private void populatePeopleArrayList() 
	{
		_people = new ArrayList<String>();

		// Get a cursor with all people
		Uri mContacts = People.CONTENT_URI;
		Cursor cursor = getContentResolver().query(mContacts, null, null, null, null);
		startManagingCursor(cursor);
		cursor.moveToFirst();
		
		do
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contact = cursor.getString(nameFieldColumnIndex);
			_people.add(contact);
			
		}while(cursor.moveToNext());
	}

	/**
	 * Populates the phone text field
	 */
	private void populatePhoneField()
	{
		String name = _friendPeopleText.getText().toString();

		Uri mContacts = People.CONTENT_URI;
		Cursor cursor = getContentResolver().query(mContacts, null, null, null, null);
		startManagingCursor(cursor);
		cursor.moveToFirst();

		do
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contactName = cursor.getString(nameFieldColumnIndex);
			
			if( name.compareTo(contactName) == 0) 
			{
				int numberFieldColumnIndex = cursor.getColumnIndex(People.NUMBER);
				String phone = cursor.getString(numberFieldColumnIndex);
				
				_friendPhoneText.setText(phone);
				break;
			}
			
		}while(cursor.moveToNext());
	}

	/**
	 * Populates the e-mail text field
	 */
	private void populateEmailField() 
	{
		String name = _friendPeopleText.getText().toString();

		Uri mContacts = Contacts.ContactMethods.CONTENT_URI;
		Cursor cursor = getContentResolver().query(mContacts, null, null, null, null);
		startManagingCursor(cursor);
		cursor.moveToFirst();

		do
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contactName = cursor.getString(nameFieldColumnIndex);
			
			if( name.compareTo(contactName) == 0) 
			{
				int emailFieldColumnIndex = cursor.getColumnIndex(Contacts.ContactMethods.DATA);
				String email = cursor.getString(emailFieldColumnIndex);
				
				_friendEmailText.setText(email);
				break;
			}
			
		}while(cursor.moveToNext());
	}


	/**
	 * Populates the field of the view when editing an existent task
	 */
	private void populateFields() 
	{
		_friendPeopleText.setOnKeyListener(new View.OnKeyListener() 
		{
			
			/* (non-Javadoc)
			 * @see android.view.View.OnKeyListener#onKey(android.view.View, int, android.view.KeyEvent)
			 */
			public boolean onKey(View v, int keyCode, KeyEvent event)  
			{
				Log.v(TAG,"the key code is: " +keyCode);
		             if (keyCode == KeyEvent.KEYCODE_DEL)
		             {
		            	 _friendPhoneText.setText(EMPTY_STRING);
		            	 _friendPhoneText.setEnabled(true);
		            	 
		            	 _friendEmailText.setText(EMPTY_STRING);
		            	 _friendEmailText.setEnabled(true);
		             }
					return false;
			}
		});

		
		_friendPhoneText.setOnTouchListener(new View.OnTouchListener() 
		{

			/* (non-Javadoc)
			 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
			 */
			@Override
			public boolean onTouch(View v, MotionEvent event) 
			{
				populatePhoneField();
				if(contactExistsByName(_friendPeopleText.getText().toString())) 
				{
					_friendPhoneText.setEnabled(false);	
				}
				return false;
			}
		});
	
		_friendEmailText.setOnTouchListener(new View.OnTouchListener() 
		{

			/* (non-Javadoc)
			 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
			 */
			@Override
			public boolean onTouch(View v, MotionEvent event) 
			{
				populateEmailField();
				if(contactExistsByName(_friendPeopleText.getText().toString())) 
				{
					_friendEmailText.setEnabled(false);
					
				}
				return false;
			}

		});
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() 
	{
		// TODO Auto-generated method stub
		super.onPause();
		saveState();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() 
	{
		// TODO Auto-generated method stub
		super.onResume();
		populateFields();
	}


	/**
	 * Saves the data in case the application is suspended
	 */
	private void saveState() 
	{
		//String course = _friendCourseText.getText().toString();
		String name = _friendPeopleText.getText().toString();
		String email = _friendEmailText.getText().toString();
		String phone = _friendPhoneText.getText().toString();
		
		String classmate = CLASSMATE_STRING;
		
		
		if(name.length() == 0 ||
				email.length() == 0 ||
				phone.length() == 0 ||
				_confirmButton.isPressed() == false) 
		{
			Log.v(TAG,"Nothing in here returning nothing");
			return;
		}

		if (contactExistsByName(name) == false)  
		{
			Log.v(TAG,"SAVING course: "+classmate);
			addNewContactToPhone(classmate,name,phone,email);
		} 
		else 
		{
			Log.v(TAG,"UPDATING course: "+classmate);
			addExistentContactToPhone(classmate,name,phone,email);
		}
	}

	/**
	 * Check if a contact exists on the phone
	 * 
	 * @param name Name of the phone contact
	 * @return true if name of contact exists in phone
	 */
	private boolean contactExistsByName(String name) 
	{
		Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
		startManagingCursor(cursor);
		cursor.moveToFirst();

		do
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contactName = cursor.getString(nameFieldColumnIndex);
			
			if( name.compareTo(contactName) == 0) {
				return true;
			}
		
		}while(cursor.moveToNext());

		return false;
	}

	/**
	 * Get id if a contact exists on the phone
	 * 
	 * @param name Name of the phone contact
	 * @return true if name of contact exists in phone
	 */
	private long getContactIdByName(String name) {

		Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
		startManagingCursor(cursor);
		cursor.moveToFirst();

		long id = -1;
		
		do
		{
			int nameFieldColumnIndex = cursor.getColumnIndex(People.NAME);
			String contactName = cursor.getString(nameFieldColumnIndex);
			
			if( name.compareTo(contactName) == 0) 
			{
				int idFieldColumnIndex = cursor.getColumnIndex(People._ID);
				id = cursor.getLong(idFieldColumnIndex);
				
				break;
			}
			
		}while(cursor.moveToNext());

		return id;
	}

	/**
	 * Add a new contact to the phone and the friend's list
	 * 
	 * @param label course for the contact
	 * @param name name of the contact
	 * @param phone phone number of the contact
	 * @param email email of the contact
	 */
	private void addNewContactToPhone(String label, String name, String phone, String email)
	{
		ContentValues values = new ContentValues();

		values.put(People.NAME, name);
		values.put(People.NOTES, label); 
		// 1 = the new contact is added to favorites
		// 0 = the new contact is not added to favorites
		//values.put(People.STARRED, 1);

		Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
		Log.v(TAG, "URI: "+uri.toString());

		Uri phoneUri = null;
		Uri emailUri = null;

		phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
		Log.v(TAG, "phone URI: "+phoneUri.toString());


		values.clear();
		values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE);
		values.put(People.Phones.NUMBER, phone);
		getContentResolver().insert(phoneUri, values);

		// Now add an email address in the same way.
		emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTORY);
		Log.v(TAG, "email URI: "+emailUri.toString());


		values.clear();
		// ContactMethods.KIND is used to distinguish different kinds of
		// contact methods, such as email, IM, etc. 
		values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);
		values.put(People.ContactMethods.DATA, email);
		values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOME);
		getContentResolver().insert(emailUri, values);  	
		 	
	}


	/**
	 * Add a existent contact to the friend's list
	 * 
	 * @param label course for the contact
	 * @param name name of the contact
	 * @param phone phone number of the contact
	 * @param email email of the contact
	 */
	private void addExistentContactToPhone(String label,String name, String phone, String email)
	{
		//appending recNo, record to be updated
		long id = getContactIdByName(name);

		Uri updateContactUri = Uri.withAppendedPath(Contacts.People.CONTENT_URI, String.valueOf(id)); 
		Log.v(TAG, "URI update: "+updateContactUri.toString());
		
		Cursor people = getContentResolver().query(updateContactUri, null, null, null, null);
		people.moveToFirst();
	
		ContentValues values = new ContentValues();
		
		do 
		{
			int notesFieldColumnIndex = people.getColumnIndex(People.NOTES);
			String notesContent = people.getString(notesFieldColumnIndex);
			
			if( notesContent == null ) 
			{
				values.clear();
				values.put(People.NOTES,label);
				getContentResolver().update(updateContactUri, values, null,null	);				
				
				Log.v(TAG,"UPDATE empty CONTACT");
				
				return;
			}
			else if(notesContent != null && notesContent.contains(CLASSMATE_STRING) == false) 
			{
				String addedTagNote = CLASSMATE_STRING + " " + notesContent;
				
				values.clear();
				values.put(People.NOTES,addedTagNote);
				getContentResolver().update(updateContactUri, values, null,null	);
				
				Log.v(TAG,"UPDATE full CONTACT");
				
				return;
			}
			
		}while(people.moveToNext());
	}
}
